﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using Intorise.Framework;

namespace Intorise.Common
{
    public class Loger
    {
        private static Security security = new Security();

        string fullFilename;
        StreamWriter writer;
        bool useBuffer = false;

        /// <summary>
        /// 是否使用缓存
        /// </summary>
        public bool UseBuffer
        {
            get { return useBuffer; }
            set { useBuffer = value; }
        }

        public Loger(string fullFilename)
        {
            Init(fullFilename);
        }

        public void Write(string message)
        {
            writer.WriteLine(message);
        }

        private void Init(string fullFilename)
        {
            this.fullFilename = fullFilename;
            FileStream stream = new FileStream(this.fullFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            writer = new StreamWriter(stream, Encoding.UTF8);
            writer.AutoFlush = !useBuffer;
            writer.WriteLine(DateTime.Now.ToString("yyyyMMdd hh:mm:ss") + "  程序已启动，日志记录已启动.");
            Process p = Process.GetCurrentProcess();
            p.EnableRaisingEvents = true;
            Application.ApplicationExit += Application_ApplicationExit;
        }

        void Application_ApplicationExit(object sender, EventArgs e)
        {
            try
            {
                writer.WriteLine(DateTime.Now.ToString("yyyyMMdd hh:mm:ss") + "  程序已退出，日志记录已退出.");
                writer.Flush();
                writer.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
